package com.ziyun.erp.web.modules.otherAccessory.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;

import io.renren.common.validator.ValidatorUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ziyun.erp.modules.otherAccessory.entity.OtherAccessoryEntity;
import com.ziyun.erp.modules.otherAccessory.service.OtherAccessoryService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 其余附件
 *
 * @author gaosheng
 * @email 
 * @date 2018-09-06 09:21:40
 */
@RestController
@RequestMapping("otherAccessory/otheraccessory")
public class OtherAccessoryController {

    @Autowired
    private OtherAccessoryService otherAccessoryService;

    @Value("${oss.host}")
    private String ossHost;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("otherAccessory:otheraccessory:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = otherAccessoryService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("otherAccessory:otheraccessory:info")
    public R info(@PathVariable("id") Integer id){
        OtherAccessoryEntity otherAccessory = otherAccessoryService.selectById(id);

        return R.ok().put("otherAccessory", otherAccessory);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("otherAccessory:otheraccessory:save")
    public R save(@RequestBody OtherAccessoryEntity otherAccessory){
        otherAccessoryService.insert(otherAccessory);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody OtherAccessoryEntity otherAccessory){
        ValidatorUtils.validateEntity(otherAccessory);
        otherAccessoryService.updateAllColumnById(otherAccessory);//全部更新
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
//    @RequiresPermissions("otherAccessory:otheraccessory:delete")
    public R delete(@RequestBody Integer[] ids){
        otherAccessoryService.deleteOtherAccessory(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 查询图片列表
     * @param params
     * @return
     */
    @RequestMapping("/imageslist")
    public R imageslist(@RequestParam Map<String, Object> params){
        return otherAccessoryService.queryImageList(params);
    }

    /**
     * 附件下载
     *
     * @param id
     * @param request
     * @param response
     */
    @RequestMapping("/download/{id}")
    public void uploadAccessorys(@PathVariable("id") Integer id, HttpServletRequest request,
                                 HttpServletResponse response) {
        OtherAccessoryEntity otherAccessory = otherAccessoryService.selectById(id);

        String accessoryUrl = ossHost + "/" + otherAccessory.getImageUrl();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        HttpURLConnection conn = null;
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            // 清除response中的缓存
            response.reset();
            // 根据网络文件地址创建URL
            URL url = new URL(accessoryUrl);
            // 获取此路径的连接
            conn = (HttpURLConnection) url.openConnection();
            // 获取文件大小
            Long fileLength = conn.getContentLengthLong();
            response.setHeader("Content-disposition",
                    "attachment; filename=" + URLEncoder.encode(otherAccessory.getName(), "UTF-8"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            // 构造读取流
            bis = new BufferedInputStream(conn.getInputStream());
            // 构造输出流
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[1024];
            int bytesRead;

            // 每次读取缓存大小的流，写到输出流
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            // 将所有的读取的流返回给客户端
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
}
